<?php
// +----------------------------------------------------------------------
// | TwoThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.twothink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 艺品网络 <http://www.twothink.cn>
// +----------------------------------------------------------------------

namespace app\home\controller;
use app\user\api\UserApi;
use app\home\model\Pay;
/**
 * 用户控制器
 * 包括用户中心，用户登录及注册
 */
class User extends Home {

	/* 用户中心首页 */
	public function index(){
		
	}

	/* 注册页面 */
	public function register($username = '', $password = '', $repassword = '', $email = '', $verify = ''){
        if(!config('user_allow_register')){
            $this->error('注册已关闭');
        }
		if($this->request->isPost()){ //注册用户
			/* 检测验证码 */
		   if(!captcha_check($verify)){
                $this->error('验证码输入错误！');
            }

			/* 检测密码 */
			if($password != $repassword){
				$this->error('密码和重复密码不一致！');
			}			

			/* 调用注册接口注册用户 */
            $User = new UserApi;
			$uid = $User->register($username, $password, $email); 
			if(0 < $uid){ //注册成功
				//TODO: 发送验证邮件
				$this->success('注册成功！',url('login'));
			} else { //注册失败，显示错误信息
				$this->error($uid);
			}

		} else { //显示注册表单
			return $this->fetch();
		}
	}

	/* 登录页面 */
	public function login($username = '', $password = '', $verify = ''){
		if($this->request->isPost()){ //登录验证
			/* 检测验证码 */
		    if(!captcha_check($verify)){
                $this->error('验证码输入错误！');
            }

			/* 调用UC登录接口登录 */
			$user = new UserApi;
			$uid = $user->login($username, $password);
			 
			if(0 < $uid){ //UC登录成功
				/* 登录用户 */
				$Member = model('Member');
				if($Member->login($uid)){ //登录用户
					//TODO:跳转到登录前页面
					$this->success('登录成功！',url('Home/Index/index'));
				} else {
					$this->error($Member->getError());
				}

			} else { //登录失败
				switch($uid) {
					case -1: $error = '用户不存在或被禁用！'; break; //系统级别禁用
					case -2: $error = '密码错误！'; break;
					default: $error = '未知错误！'; break; // 0-接口参数错误（调试阶段使用）
				}
				$this->error($error);
			}

		} else { //显示登录表单
			return $this->fetch();
		}
	}

	/* 退出登录 */
	public function logout(){
		if(is_login()){
			model('Member')->logout();
			$this->success('退出成功！', url('User/login'));
		} else {
			$this->redirect('User/login');
		}
	}
 


    /**
     * 修改密码提交
     * @author 艺品网络  <twothink.cn>
     */
    public function profile(){
		if ( !is_login() ) {
			$this->error( '您还没有登陆',url('User/login') );
		}
        if ($this->request->isPost()) {
            //获取参数
            $uid        =   is_login();
            $data = input('param.'); 
            $password   =  $data['old'];;
            $repassword = $data['repassword'];
            $data['password'] = $data['password'];
            empty($password) && $this->error('请输入原密码');
            empty($data['password']) && $this->error('请输入新密码');
            empty($repassword) && $this->error('请输入确认密码');

            if($data['password'] !== $repassword){
                $this->error('您输入的新密码与确认密码不一致');
            }

            $Api = new UserApi();
            $res = $Api->updateInfo($uid, $password, $data);
            if($res['status']){
                $this->success('修改密码成功！');
            }else{
                $this->error($res['info']);
            }
        }else{
            return $this->fetch();
        }
    }

	/**
	* @author fgrass <fgrass@126.com>
	*/
	public function center(){
		if ( !is_login() ) {
			$this->error( '您还没有登陆',url('User/login') );
		}
        $uid  =  is_login();
		// $robots = \think\Db::name('f_tuling')->where('uid', $uid)->select();
		// $this->assign('robots', $robots);
		$user = \think\Db::name('member')->find($uid);
		$recharge = \think\Config::get('recharge');
		$this->assign('user', $user);
		$this->assign('recharge', $recharge);
		return $this->fetch();
	}

	public function orders(){
		if ( !is_login() ) {
			$this->error( '您还没有登陆',url('User/login') );
		}
        $uid  =  is_login();
		$orders = \think\Db::name('f_order')->where('uid',$uid)->order('create_time desc')->select();
		$this->assign('orders', $orders);
		return $this->fetch();
	}

	public function order($no=''){
		if ( !is_login() ) {
			$this->error( '您还没有登陆',url('User/login') );
		}
        $uid  =  is_login();
		$order = \think\Db::name('f_order')->find($no);
		if(!$order){
			$this->error( '订单不存在' );
		}
		$this->assign('order', $order);
		return $this->fetch();
	}

	/**
	* @author fgrass <fgrass@126.com>
	*/
	public function recharge($amount = 0, $subject = ''){
		if ( !is_login() ) {
			$this->error( '您还没有登陆',url('User/login') );
		}
		$amount = floatval($amount);
		if($amount <= 0){
			$this->error( '充值金额必须大于0');
		}
		if(!$subject){
			$subject = '充值'.$amount.'元';
		}
        $uid  =  is_login();
    	$out_trade_no = $this->build_order_no();
		//订单先入库
		$trade['uid']= $uid;
		$trade['number'] = $out_trade_no;
		$trade['subject'] = $subject;
		$trade['amount'] = $amount;
		$trade['create_time'] = time();
		$res = \think\Db::name("f_order")->insert($trade);
        if(!$res){
            return $this->error('创建订单失败！');
        }
		//调用支付接口，进行支付
		$Pay = new Pay;//实例化前请先导入类或者使用use语法  
		$result = $Pay->alipay([  
			'notify_url' => request()->domain().url('home/user/alipay_notify'),//支付结果通知地址，完整url  
			'return_url' => request()->domain().url('home/user/orders'),//同步通知地址  
			'out_trade_no' => $out_trade_no,//本站订单编号  
			'subject' => $subject,//支付标题  
			'total_fee' => $amount,//订单金额，单位为元例如：0.1  
			'body' => '充值享受更好服务',//支付说明  
		]);  
		if(!$result['code']){//模型会对提交的数据进行验证，如果code=0那么$result['msg']的结果为验  
			return $this->error($result['msg']);
		}  
		//如果验证成功，$result['msg']为支付宝提交表单，直接输出即可  
		return $result['msg'];
	}
	public function alipay_notify()  
    {//异步订单通知
        $Pay = new Pay;  
        $result = $Pay->notify_alipay();
		if($result == 'success'){
			//记录订单信息
			$out_trade_no = input('out_trade_no');
			//此订单信息是否已经更新？
			$info = \think\Db::name("f_order")->where('number', $out_trade_no)->find();
			if($info && $info['ispay'] != 1){
				//支付宝交易号
				$trade_no = input('trade_no');
				//订单金额
				$total_amount = $info['amount'];
				$trade['trade_no'] = $trade_no;
				$trade['ispay'] = 1;
				$trade['pay_time'] = time();
				\think\Db::name("f_order")->where('number', $out_trade_no)->update($trade);
				//为用户自动增加次数
				$recharge = \think\Config::get('recharge');
				$send_count = 0;
				//查找是不是套餐
				foreach($recharge as $v){
					if(abs($v['price'] - $total_amount) < 0.01){
						$send_count = $v['send_amount'];
						break;
					}
				}
				if($send_count <= 0){
					//不在套餐内
					$send_count_per = intval(\think\Config::get('send_count_per'));
					if($send_count_per <= 0){
						$send_count_per = 1000;
					}
					$send_count = $total_amount * $send_count_per;
				}
				\think\Db::name('member')->where('uid', $info['uid'])->setInc('send_max_amount', $send_count);
			}
			//\记录订单信息
		}
        exit($result);  
    }
}
